<template>
	<view class="order-submit">
		<custom-nav-bar title="提交订单" showBack></custom-nav-bar>

		<view class="address">
			<view class="method" @click="handleAddress">
				<view class="tab" v-show="false">
					<view class="text">选择收货地址</view>
					<view class="right">
						<image class="img" src="/static/icons/right-707070.png" mode="aspectFill"></image>
					</view>
				</view>
				<view class="tab address-info" v-show="true">
					<view class="left">
						<view class="name">{{ defaultAddress?.company }}</view>
						<view class="con-pho">
							<view class="consignee">{{ defaultAddress?.consignee }}</view>
							<view class="phone">{{ defaultAddress?.phone }}</view>
						</view>
					</view>
					<view class="edit-btn">
						<!-- <image class="img" src="/static/edit.png" /> -->
						<!-- <image class="img" src="/static/icons/edit.png" mode="aspectFill"></image> -->
						<image class="img" src="/static/icons/right-707070.png" mode="aspectFill"></image>
					</view>
				</view>
			</view>
			<view class="time tab" @click="handleMarkAppear">
				<view class="text">收货时间</view>
				<view class="right">

					<!-- 选择的时间时，为时间前面添加'今日'或'明日'，如果选择‘尽快送达’则不显示日期 -->
					{{ (arr[0] == 0 && arr[1] == 0 ? '' : timeArr[arr[0]].day + ' | ') + timeArr[arr[0]].time[arr[1]] }}
					<image class="img" src="/static/icons/right-707070.png" mode="aspectFill"></image>
				</view>
			</view>
		</view>

		<view class="order">
			<view class="for-order">
				<order @total="handleTotal"></order>
			</view>
		</view>

		<view class="submit">
			<view class="price-and-btn">
				<view class="price">
					<text @click="handleClick">合计</text>
					<text class="str">
						<text>￥</text>
						<text class="total">{{ total }}</text>
					</text>
				</view>
				<view class="btn" @click="handleOrderSubmit">提交订单</view>
			</view>
			<view class="bottom-save-area" :style="{ height: `${bottomSafeArea()}px` }"></view>
		</view>
		<!-- <add-to-cart></add-to-cart> -->
		<view :class="{ 'mark-bg': true, 'mark-bg-disable': markChange }" ref="mark" @click="handleMarkRemove"
			v-show="show"></view>
		<view :class="{ 'mark-border': true, 'mark-border-disable': markChange }" v-show="show">
			<view class="mark-border-header">
				<text class="close"></text>
				<text class="title">选择送达时间</text>
				<text class="close" @click="handleMarkRemove">×</text>
			</view>
			<view class="time-select">
				<view class="select-day">
					<view :class="{ day: true, 'day-active': selectDay === i }" v-for="(d, i) of timeArr" :key="d.day"
						@click="selectDay = i">
						{{ d.day }}
					</view>
				</view>
				<!-- <view class="scroll-view"> -->
				<scroll-view scroll-y="true" class="scroll-view" :show-scrollbar="false">
					<view class="time-list">
						<view
							:class="{ 'time-item': true, 'time-item-active': arr[0] === selectDay && arr[1] === index && item !== '今日无法送达' }"
							v-for="(item, index) of timeArr[selectDay].time" :key="item" @click="handlesSelectTime(index, item)">{{
								item }}</view>
					</view>
				</scroll-view>
				<!-- </view> -->
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { bottomSafeArea } from '../../utils/system';
import { funGetTimeRange30 } from '../../utils/funGetTimeRange30';
import { useAddress } from '@/stores/address.js'
import { useTimePay } from '../../stores/timePay';
import { useSubmitData } from '../../stores/submitData';


const store = useAddress()

// 提交订单时间
const timePay = useTimePay()

// 提交订单数据
const submitData = useSubmitData()


const handleAddress = () => {

	uni.navigateTo({
		url: '/pages/address/address'
	})
}


const handleClick = () => {
	console.log(defaultAddress.value);

}

const show = ref(false);
const mark = ref(null);
const markChange = ref(true);
let timer = null;

// 出现选择时间
const handleMarkAppear = () => {
	show.value = true;
	timer = setTimeout(() => {
		markChange.value = false;
		timer = null;
	});
};

// 关闭选择时间
const handleMarkRemove = () => {
	// 当有定时器时，不执行该函数，
	if (timer) {
		return;
	}
	markChange.value = true;
	timer = setTimeout(() => {
		show.value = false;
		timer = null;

		// 定时时间为设置的css动画过度时间
	}, 300);
};



// 获取当前时间
const now = new Date();

// 获取当天送餐时间段数组
const today = ref(funGetTimeRange30(now));

if (today.value.length) {
	const time = new Date(now.getTime() + 1000 * 60 * 15);
	today.value.unshift(`尽快送达 | ${String(time.getHours()).padStart(2, '0')}:${String(time.getMinutes()).padStart(2, '0')}`)
}
else {
	today.value.unshift('今日无法送达')
}

// 获取明天送餐时间段数组，早上8点开始
const tomorrow = ref(funGetTimeRange30(new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8)));

// 时间段数组
const timeArr = ref([{ day: '今日', time: today.value }, { day: '明日', time: tomorrow.value }]);

// 选中的天数
const selectDay = ref(0)

// 天数被选中
const handleSelectDay = (i) => {
	selectDay.value = i
}

const arr = ref([0, 0])

// 选择时间
const handlesSelectTime = (i, item) => {
	if (item === '今日无法送达') {
		uni.showToast({
			title: '请选择其他时间',
			icon: 'none'
		})
		return
	}
	arr.value = [selectDay.value, i]
	handleMarkRemove()
}


// 总价
const total = ref(0)
// 向父组件传递总价
const handleTotal = (price) => {
	total.value = price
	console.log(total.value);
}


class Address {
	constructor(id, company, consignee, phone, isDefault, sex) {
		this.id = id;
		this.company = company;
		this.consignee = consignee;
		this.phone = phone;
		this.isDefault = isDefault;
		this.sex = sex;
	}
}


// 获取地址列表的同时，将地址存储到本地存储中
const getAddressList = async () => {
	// try {
	//   const res = await apiGet('/user/addressBook/list')
	//   if (res.code === 200) {
	//     addressList.value = res.data;
	//   }
	// } catch (error) {
	//   console.error('获取地址列表失败', error);
	// }
	// try {
	//   const res = await apiGet('/user/addressBook/list')
	//   if (res.code === 200) {
	//     addressList.value = res.data;
	//   }
	// } catch (error) {
	//   console.error('获取地址列表失败', error);
	// }

	// store.add

	const arrList = [
		...Array.from({ length: 5 }, (_, index) => {
			return new Address(String(index + 1), `地址${index + 1}`, `联系人${index + 1}`, `1234567890${index + 1}`, (index ? 1 : 0), 0);
		})
	]
	if (store.addressList.length === 0) {
		store.addAddressList(arrList)
	}
};

// 页面加载时获取地址列表
onMounted(() => {
	getAddressList();
})

// 获取选中的默认地址
const defaultAddress = computed(() => store.addressList?.find(e => !e.isDefault))




// 提交订单
const handleOrderSubmit = () => {
	uni.navigateTo({
		url: '/pages/pay/pay'
	})

	// 提交订单后，储存当前时间戳
	timePay.setTime(Date.now())

	// 提交订单后，将订单的一些数据，如订单号等，存储到本地存储中
	submitData.setSubmitData({
		id: 'kjd8247shd74hda',
		orderAmount: total.value,
		orderNumber: '202307010001',
		orderTime: new Date()

	})
}

</script>
<style scoped lang="scss">
.order-submit {
	padding: 20rpx;
	background-color: #f1f1f1;
	min-height: 100vh;
	box-sizing: border-box;
	position: relative;

	.address {
		padding: 0 20rpx;
		border-radius: 20rpx;
		background-color: #fff;

		.tab {
			min-height: 100rpx;
			display: flex;
			box-sizing: border-box;
			padding: 0 20rpx;
			justify-content: space-between;
			align-items: center;

			.right {
				display: flex;
				align-items: center;
				flex-direction: row;
				color: #999;

				.img {
					width: 40rpx;
					height: 40rpx;
				}
			}
		}

		.method {
			border-bottom: #ddd 1px solid;
			color: #ff4f51;
			font-size: 38rpx;
			font-weight: 600;

			.address-info {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 24rpx 10rpx;

				.left {
					display: flex;
					flex-direction: column;
					gap: 10rpx;

					.name {
						font-size: 38rpx;
						font-weight: bold;
						color: #000;
					}

					.con-pho {
						display: flex;
						align-items: center;
						gap: 20rpx;
						flex-direction: row;
						font-size: 30rpx;

						.consignee {
							color: #999;
						}

						.phone {
							color: #999;
						}
					}


				}

				.edit-btn {
					color: #1aad19;
					cursor: pointer;

					.img {
						width: 45rpx;
						height: 45rpx;
					}
				}
			}
		}
	}

	.order {
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;

		// width: 100%;
	}

	.submit {
		// min-height: 100rpx;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		width: 100%;
		left: 0;
		display: flex;
		padding-top: 20rpx;
		box-sizing: border-box;
		flex-direction: column;

		.price-and-btn {
			display: flex;
			flex-direction: row;
			align-items: center;
			margin-right: 10rpx;
			gap: 20rpx;
			justify-content: flex-end;
			width: 100%;
			box-sizing: border-box;
			padding-right: 30rpx;
			// margin-right: 30rpx;

			.price {
				font-size: 30rpx;

				.str {
					font-weight: 600;

					.total {
						font-size: 46rpx;
					}
				}
			}

			.btn {
				background-color: #ffebcd;
				padding: 18rpx 44rpx;
				border-radius: 100rpx;
				font-size: 36rpx;
			}
		}
	}

	.mark-bg {
		position: absolute;
		opacity: 0.4;
		background-color: #444;
		height: 100vh;
		width: 100%;
		top: 0;
		left: 0;
		transition: all 0.3s;
		z-index: 101;
	}

	.mark-border {
		height: 900rpx;
		background-color: #fff;
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 102;
		transition: all 0.3s;
		border-radius: 50rpx 50rpx 0 0;
		display: flex;
		flex-direction: column;

		.mark-border-header {
			display: flex;
			justify-content: space-between;
			padding: 30rpx 40rpx;
			align-items: center;
			height: 100rpx;
			box-sizing: border-box;
			// flex-direction: c;

			.title {
				font-size: 38rpx;
				font-weight: 600;
			}

			.close {
				font-size: 60rpx;
				width: 50rpx;
				height: 50rpx;
				line-height: 50rpx;
			}
		}

		.time-select {
			display: flex;
			flex-grow: 1;


			.select-day {
				background-color: #eee;
				height: 100%;
				width: 180rpx;
				// flex-grow: 1;

				.day {
					height: 80rpx;
					text-align: center;
					line-height: 80rpx;
				}

				.day-active {
					background-color: #fff;
				}
			}

			// .scroll-view {
			// flex-grow: 1;

			.scroll-view {
				height: 800rpx;
				// padding: 0 30rpx;
				// box-sizing: border-box;

				.time-list {
					flex-grow: 1;
					background-color: #fff;
					padding: 0 30rpx;
					display: flex;
					flex-direction: column;
					gap: 20rpx;


					.time-item {
						height: 90rpx;
						line-height: 80rpx;
						border-bottom: 1px solid #dfdfdf;
						// color: #FF4F51;
						// background-color: #444;
					}

					.time-item-active {
						color: #FF4F51;
					}
				}
			}

			// }
		}
	}

	.mark-bg-disable {
		opacity: 0;
		transition: all 0.3s;
	}

	.mark-border-disable {
		transform: translateY(900rpx);
		transition: all 0.3s;
	}
}
</style>
<style></style>
